"""
音频处理记录数据访问层
"""
from typing import Optional, List
from sqlalchemy.orm import Session
from sqlalchemy import desc

from app.databases.models import AudioProcessingRecord
from app.repositories.base import BaseRepository


class AudioProcessingRepository(BaseRepository[AudioProcessingRecord]):
    """音频处理记录Repository"""
    
    def __init__(self, db: Session):
        super().__init__(AudioProcessingRecord, db)
    
    def get_by_filename(self, filename: str) -> Optional[AudioProcessingRecord]:
        """根据文件名获取记录"""
        return self.db.query(self.model).filter(
            self.model.filename == filename
        ).first()
    
    def get_by_status(self, status: str) -> List[AudioProcessingRecord]:
        """根据状态获取记录列表"""
        return self.db.query(self.model).filter(
            self.model.status == status
        ).all()
    
    def get_recent_records(self, limit: int = 10) -> List[AudioProcessingRecord]:
        """获取最近的记录"""
        return self.db.query(self.model).order_by(
            desc(self.model.created_at)
        ).limit(limit).all()
    
    def get_by_user_and_timeframe(
        self, 
        user_id: Optional[int] = None,
        start_time: Optional[str] = None,
        end_time: Optional[str] = None
    ) -> List[AudioProcessingRecord]:
        """根据用户和时间范围获取记录"""
        query = self.db.query(self.model)
        
        if user_id:
            query = query.filter(self.model.user_id == user_id)
        
        if start_time:
            query = query.filter(self.model.created_at >= start_time)
        
        if end_time:
            query = query.filter(self.model.created_at <= end_time)
        
        return query.order_by(desc(self.model.created_at)).all()
    
    def update_status(
        self, 
        record_id: int, 
        status: str, 
        processing_time: Optional[float] = None,
        error_message: Optional[str] = None
    ) -> Optional[AudioProcessingRecord]:
        """更新处理状态"""
        record = self.get(record_id)
        if record:
            update_data = {"status": status}
            if processing_time is not None:
                update_data["processing_time"] = processing_time
            if error_message is not None:
                update_data["error_message"] = error_message
            
            return self.update(record, update_data)
        return None
    
    def get_statistics(self) -> dict:
        """获取处理统计信息"""
        total_count = self.count()
        success_count = self.count({"status": "completed"})
        failed_count = self.count({"status": "failed"})
        pending_count = self.count({"status": "pending"})
        
        return {
            "total": total_count,
            "success": success_count,
            "failed": failed_count,
            "pending": pending_count,
            "success_rate": (success_count / total_count * 100) if total_count > 0 else 0
        }
